<template>
  <el-dialog
    top="80px"
    :visible.sync="isVisible"
    :title="title"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-container>
      <el-main
        v-loading="submitLoading"
        :style="{ 'max-height': maxHeightDialog }"
        :element-loading-text="submitLoading ? '提交中...' : '加载中...'"
        class="container-main"
      >
        <div>
          <div class="title">
            <span>填写信息</span>
          </div>

          <el-card
            class="card"
            shadow="never"
            style="background: #fafafa;"
          >
            <div style="margin-left: -12px; margin-right: -12px">
              <el-row>
                <el-col :span="23">
                  <el-form
                    ref="elForm"
                    size="small"
                    label-position="right"
                    :model="form"
                    :rules="rules"
                    label-width="120px"
                  >
                    <el-row>
                      <el-col :span="24">
                        <el-form-item label="所属省">
                          <el-select
                            v-model="form.province"
                            placeholder="请选择所属省"
                            filterable
                            clearable
                            style="width: 100%"
                            @change="getCityList(true)"
                          >
                            <el-option
                              v-for="item of provinceList"
                              :key="item.codeId"
                              :label="item.positionName"
                              :value="item.positionName"
                            /> </el-select
                        ></el-form-item>
                      </el-col>
                    </el-row>

                    <el-row>
                      <el-col :span="24">
                        <el-form-item label="所属地市">
                          <el-select
                            v-model="form.city"
                            placeholder="请选择地市"
                            filterable
                            clearable
                            style="width: 100%"
                            @change="getCountyList(true)"
                          >
                            <el-option
                              v-for="item of cityList"
                              :key="item.codeId"
                              :label="item.positionName"
                              :value="item.positionName"
                            />
                          </el-select>
                        </el-form-item>
                      </el-col>
                    </el-row>

                    <el-row>
                      <el-col :span="24">
                        <el-form-item label="所属区县">
                          <el-select
                            v-model="form.area"
                            placeholder="请选择区县"
                            filterable
                            clearable
                            style="width: 100%"
                          >
                            <el-option
                              v-for="item of countyList"
                              :key="item.codeId"
                              :label="item.positionName"
                              :value="item.positionName"
                            />
                          </el-select>
                        </el-form-item>
                      </el-col>
                    </el-row>

                    <el-row>
                      <el-col :span="24">
                        <el-form-item label="场所名称" prop="placeName">
                          <el-input
                            v-model="form.placeName"
                            placeholder="请输入场所名称"
                            clearable
                          />
                        </el-form-item>
                      </el-col>
                    </el-row>

                    <el-row>
                      <el-col :span="24">
                        <el-form-item label="地址" prop="address">
                          <el-input
                            v-model="form.address"
                            placeholder="请输入地址"
                            clearable
                          />
                        </el-form-item>
                      </el-col>
                    </el-row>

                    <el-row>
                      <el-col :span="24">
                        <el-form-item label="位置">
                          <el-input
                            v-model="form.location"
                            placeholder="请输入位置"
                            @focus="getLocation"
                          />
                        </el-form-item>
                      </el-col>
                    </el-row>

                    <el-row>
                      <el-col :span="24">
                        <el-form-item label="负责人" prop="manager">
                          <el-input
                            v-model="form.manager"
                            placeholder="请输入负责人"
                            clearable
                          />
                        </el-form-item>
                      </el-col>
                    </el-row>

                    <el-row>
                      <el-col :span="24">
                        <el-form-item label="联系电话" prop="contactNum">
                          <el-input
                            v-model="form.contactNum"
                            placeholder="请输入联系电话"
                            clearable
                          />
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </el-form>
                </el-col>
              </el-row>
            </div>
          </el-card>
        </div>
      </el-main>

      <el-footer>
        <el-button
          size="medium"
          icon="el-icon-close"
          :disabled="submitLoading"
          style="width: 120px; margin-right: 10px"
          @click="isVisible = false"
        >
          取消
        </el-button>
        <el-button
          size="medium"
          type="primary"
          icon="el-icon-check"
          :disabled="submitLoading"
          :loading="submitLoading"
          style="width: 120px"
          @click="toSubmit"
        >
          {{ params.type == 'edit' ? '修改' : '提交' }}
        </el-button>
      </el-footer>
    </el-container>

    <Map
      v-if="isShowMap"
      :dialog-visible="isShowMap"
      :longitude="longitude"
      :latitude="latitude"
      @close="dialogShowMapClose()"
      @save="toSaveLocation"
    />
  </el-dialog>
</template>

<script>
import dataFormMixins from '@/mixins/data-form-mixins'
import GridManageApi from '@/api/grid-manage'
import { validMobile } from '@/utils/my-validate'
import EpidemicPreventionManageApi from '@/api/epidemic-prevention-manage'
import Map from './Map'

export default {
  name: 'PlaceRecordsAdd',
  components: {
    Map,
  },
  mixins: [dataFormMixins],
  props: {
    dialogVisible: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: '',
    },
    params: {
      type: Object,
      default: () => {
        return {}
      },
    },
  },
  data() {
    return {
      provinceList: [],
      cityList: [],
      countyList: [],

      isShowMap: false,
      longitude: '',
      latitude: '',
    }
  },
  computed: {
    isVisible: {
      get() {
        return this.dialogVisible
      },
      set() {
        this.toClose()
      },
    },
  },
  mounted() {
    this.form = this.initForm()
    this.rules = this.initRules()
    this.getProvinceList()
    if (this.params.type === 'edit') {
      Object.keys(this.form).forEach((key) => {
        Object.keys(this.params.item).forEach((_key) => {
          if (key == _key) {
            this.form[key] = this.params.item[_key]
          }
        })
      })
    }
  },
  methods: {
    initForm() {
      return {
        id: '',
        tenantId: '', // 租户ID
        province: '', // 所属省
        provinceCode: '', // 省级区划编号
        city: '', // 所属市
        cityCode: '', // 市级区划编号
        area: '', // 所属区县
        areaCode: '', // 区县区划编号
        town: '', // 街道(乡镇)
        townCode: '', // 乡镇区划编号
        village: '', // 社区(村)
        villageCode: '', // 社区区划编号
        placeName: '', // 场所名称
        address: '', // 地址
        location: '', // 位置
        manager: '', // 负责人
        contactNum: '', // 联系电话
      }
    },
    initRules() {
      return {
        placeName: this.getValidatorForm(),
        address: this.getValidatorForm(),
        manager: this.getValidatorForm(),
        contactNum: this.getValidatorForm(),
      }
    },

    getProvinceList() {
      const data = {
        label: 'level',
        value: 1,
      }
      GridManageApi.getPositionList(data).then((ret) => {
        this.provinceList = ret.data.data
        if (this.form.province && this.form.province !== '') {
          this.getCityList(false)
        }
      })
    },
    getCityList(bool) {
      if (bool) {
        this.cityList = []
        this.countyList = []
        this.form.city = ''
        this.form.county = ''
      }
      const data = {
        label: 'parentCodeId',
        value: '',
      }

      this.provinceList.forEach((ele) => {
        if (ele.positionName === this.form.province) {
          data.value = ele.codeId
        }
      })
      GridManageApi.getPositionList(data).then((ret) => {
        this.cityList = ret.data.data
        if (this.form.city && this.form.city !== '') {
          this.getCountyList(false)
        }
      })
    },
    getCountyList(bool) {
      if (bool) {
        this.countyList = []
        this.form.county = ''
      }

      const data = {
        label: 'parentCodeId',
        value: '',
      }
      this.cityList.forEach((ele) => {
        if (ele.positionName === this.form.city) {
          data.value = ele.codeId
        }
      })
      GridManageApi.getPositionList(data).then((ret) => {
        this.countyList = ret.data.data
      })
    },

    getLocation() {
      this.isShowMap = true
      if (this.form.location && this.form.location != '') {
        if (this.form.location.indexOf(',') > -1) {
          this.longitude = this.form.location.split(',')[0]
          this.latitude = this.form.location.split(',')[1]
        }
      }
    },
    dialogShowMapClose() {
      this.isShowMap = false
    },
    toSaveLocation(data) {
      this.form.location = data
    },

    toClose() {
      this.$emit('close')
    },
    toSubmit() {
      this.$refs.elForm.validate((valid) => {
        console.log('form', this.form)
        if (valid) {
          const model = this.formatFormData(this.form)

          model.provinceCode = this.getCodeId(this.provinceList, 'province', 2)
          model.cityCode = this.getCodeId(this.cityList, 'city', 4)
          model.areaCode = this.getCodeId(this.countyList, 'area', 6)

          console.log('model=', model)

          if (!validMobile(this.form.contactNum)) {
            this.$message({
              message: '联系电话输入的值不正确，请重新输入',
              type: 'warning',
              duration: 4000,
            })
            return
          }

          this.submitLoading = true
          if (this.params.type === 'add') {
            EpidemicPreventionManageApi.addPlace(model)
              .then((res) => {
                if (res.data.code == 200) {
                  this.$message({
                    message: '提交成功！',
                    type: 'success',
                  })
                  this.submitLoading = false
                  this.isVisible = false
                  this.$emit('submit', 'add')
                } else {
                  this.$message({
                    message: '提交失败！',
                    type: 'error',
                  })
                  this.submitLoading = false
                }
              })
              .catch(() => {
                this.submitLoading = false
              })
          } else {
            EpidemicPreventionManageApi.updatePlace(model)
              .then((res) => {
                if (res.data.code == 200) {
                  this.$message({
                    message: '修改成功！',
                    type: 'success',
                  })
                  this.submitLoading = false
                  this.isVisible = false
                  this.$emit('submit', 'edit')
                } else {
                  this.$message({
                    message: '修改失败！',
                    type: 'error',
                  })
                  this.submitLoading = false
                }
              })
              .catch(() => {
                this.submitLoading = false
              })
          }
        } else {
          this.$message({
            message: '*必填项不能为空！',
            type: 'warning',
            duration: 4000,
          })
          return false
        }
      })
    },
    getCodeId(list, key, num) {
      let code = ''
      list.forEach((ele) => {
        if (ele.positionName == this.form[key]) {
          code = ele.codeId.toString().slice(0, num)
        }
      })
      return code
    },
  },
}
</script>

<style scoped lang="scss">
@import '../../../../../styles/part-custom';
</style>
